package com.thekernel.youdaoyun.service.impl;

import com.thekernel.youdaoyun.bean.Star;
import com.thekernel.youdaoyun.exception.MyException;
import com.thekernel.youdaoyun.exception.impl.IllegalUserException;
import com.thekernel.youdaoyun.mapper.StarMapper;
import com.thekernel.youdaoyun.service.StarService;
import com.thekernel.youdaoyun.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author TheKernel
 * @Date 2019/9/13 7:39 下午
 * @Version 1.0
 * @Description StarService 的具体实现
 */
@Service("StarService")
public class StarServiceImpl implements StarService {

    @Autowired
    private StarMapper starMapper;

    /**
     * 添加收藏
     * @param star 收藏信息(star_note, star_user必需)
     * @return -1: Data Not Found 0: Star Already Exists 1: Success
     */
    @Override
    public int addStar(Star star) {
        // 检测数据是否完善
        if (star.getStarNote() == 0 || star.getStarUser() == 0) {
            return -1;
        }
        // 检测 star 是否已存在
        if (this.starMapper.queryStarIdByStarUserAndStarNote(star) != null) {
            return 0;
        }
        // 生成 star
        star.setStatus(Boolean.TRUE);
        star.setCreateTime(new Date());
        // 添加 star
        return this.starMapper.add(star);
    }

    /**
     * 取消收藏
     *
     * @param starId 收藏 id
     * @return -1: Data Not Found 0: Star Not Found 1: Success
     */
    @Override
    public int cancelStar(long starId, long userId) throws MyException {
        // 检测数据是否完善
        if (starId == 0) {
            return -1;
        }
        // 检测 star 是否属于该用户
        if (this.starMapper.queryStarByStarId(starId).getStarUser() != userId) {
            throw new IllegalUserException();
        }
        // 删除 star
        return this.starMapper.cancelStarByStarId(starId);
    }

    /**
     * 查询收藏
     * @return 收藏列表
     * @throws MyException 非本人操作等
     */
    @Override
    public Star[] queryStar() throws MyException {
        long userId = UserUtils.checkReturnUserId();

        return this.starMapper.queryAllStars(userId);
    }
}
